package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {
//因为要查数据库,所以必须注入Mapper
    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImagerMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseTradeMarkMapper baseTradeMarkMapper;

    @Autowired
    private RedisTemplate redisTemplate;
//    @Autowired
//    private RedisClient redisClient;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 第九天:全局检索
     */
    //获取品牌
    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTradeMarkMapper.selectById(tmId);
    }

    //通过skuId,查询数据
    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }

    /**
     * 第八天:首页显示
     */
    @Override
    @GmallCache(prefix = "baseCategoryList")
    public List<JSONObject> getBaseCaseCatgeoryList(){
        List<JSONObject> list = new ArrayList<>();
        /*
        1.获取所有的分类数据:select * from base_category_view
        2.根据分类Id分组,来获取数据{分类Id+分类的名称}
        3.组装成我们需要的json数据,然后添加到集合List
         */
        //1.获取所有数据:baseCategoryView是中间表
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        //2.根据分类Id分组,来获取数据 select category1Id, category1Name from base_category_view group by category1Id , category1Name;
            //map的key就是一级分类Category1Id,value对应的一级分类Id下所有数据
        Map<Long,List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        int index = 1;
        //循环遍历
        for (Map.Entry<Long, List<BaseCategoryView>> entry : category1Map.entrySet()) {
            //3.声明一个对象 JSONObject是一个Json类型的map
            JSONObject category1 = new JSONObject();
            //4.获取一级分类Id
            Long category1Id = entry.getKey();
            //5.获取一级分类的值
            List<BaseCategoryView> category2List = entry.getValue();

            category1.put("index", index);
            category1.put("categoryId", category1Id);
            //6.按照一级分类Id进行分组,所以一个组的名称都是一样
            category1.put("categoryName", category2List.get(0).getCategory1Name());
            //7.变量迭代
            index++;

            //2.1声明一个集合来存储二级分类对象数据
            List<JSONObject> category2Child = new ArrayList<>();
            //2.2获取二级分类数据
            Map<Long, List<BaseCategoryView>> category2Map = category2List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //2.3循环遍历
            for (Map.Entry<Long, List<BaseCategoryView>> longListEntry : category2Map.entrySet()) {
                //2.4声明一个对象
                JSONObject category2 = new JSONObject();
                //2.5获取二级分类的Id
                Long category2Id = longListEntry.getKey();
                //2.6获取二级分类的value
                List<BaseCategoryView> category3List = longListEntry.getValue();
                //2.7获取二级分类的名称
                String category2Name = category3List.get(0).getCategory2Name();
                //2.8给二级分类对象赋值
                category2.put("categoryId", category2Id);
                category2.put("categoryName", category2Name);
                //2.9将二级分类对象添加到集合中
                category2Child.add(category2);

                //3.获取三级分类数据
                //3.1声明一个三级分类集合对象
                List<JSONObject> category3Child = new ArrayList<>();
                //3.2循环遍历三级分类数据集合
                category3List.forEach((baseCategory3View)->{
                    //3.3声明一个三级对象集合
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", baseCategory3View.getCategory3Id());
                    category3.put("categoryName", baseCategory3View.getCategory3Name());
                    //3.4将三级分类数据添加到集合中
                    category3Child.add(category3);
            });
                //将三级分类数据添加到二级分类的集合
                category2.put("categoryChild", category3Child);
            }
            //将二级分类数据添加到一级分类的集合
            category1.put("categoryChild", category2Child);
                //将每个一级分类添加到集合
                list.add(category1);
            }
            return list;
    }


    /**
     * 第七天:加入分布式锁
     * @return
     */
    @Override
    public SkuInfo getSkuInfoById(Long skuId) {
        //  推荐使用redisson;
        return getSkuInfoRedisson(skuId);

   //     return getSkuInfoRedis(skuId);
    }

    //使用redisson做分布式锁
    private SkuInfo getSkuInfoRedisson(Long skuId){
        SkuInfo skuInfo = null;
        try {
            //定义redis中存储的key sku:skuid:info
            String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
            //从缓存中取出数据
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            //判断缓存中是否有数据
            if(skuInfo == null){
                //缓存没有数据,从数据库查找,所以需要分布式锁,防止缓存击穿
                String skuKeyLock = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(skuKeyLock);
                    //上锁
                boolean res = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //判断是否上锁
                if(res){
                    try {
                        //表示上锁,从数据库中查找数据
                        skuInfo = getSkuInfo(skuId);

                        if (skuInfo == null){//数据库中没有这个数据
                            SkuInfo skuInfo1 = new SkuInfo();
                            redisTemplate.opsForValue().set(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);

                            return skuInfo1;
                        }else {
                            redisTemplate.opsForValue().set(skuKey, skuInfo, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                            //返回查询到的数据
                            return skuInfo;
                        }
                    } finally {
                        lock.unlock();
                    }
                }else{//没有上锁
                    try {
                        //等待自旋
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return getSkuInfoById(skuId);
                }
            }else {//缓存中有数据
                return skuInfo;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //数据库兜底
        return getSkuInfo(skuId);
    }



    //使用redis做分布式锁
    private SkuInfo getSkuInfoRedis(Long skuId){
        SkuInfo skuInfo = null;
        try {
            //缓存存储数据:key-value
            //定义redis存储的key sku:skuId:info
            String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
            //去缓存中根据key查询value
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            //做判断.
            if(skuInfo == null){//缓存中没有数据
                //取数据库中查找,所以需要添加分布式锁
                    //定义锁的key
                String skuKeyLock = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                    //定义锁的值
                String uuid = UUID.randomUUID().toString();
                //创建锁
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(skuKeyLock, uuid, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                if(flag){//判断是否上锁
                    //上锁后查询数据库
                    skuInfo = getSkuInfo(skuId);
                    //判断数据库获取到的skuInfo是否为空,防止缓存穿透
                    if (skuInfo == null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        //将空的skuInfo1放入缓存,过期时间缩短
                        redisTemplate.opsForValue().set(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        //返回数据
                        return skuInfo1;
                    }
                    //数据库获取到skuInfo,放入缓存
                    redisTemplate.opsForValue().set(skuKey, skuInfo, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);

                    //使用lua脚本删除锁
                        //定义删除lua脚本
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    //赋值lua脚本
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Long.class);
                    //删除
                    redisTemplate.execute(redisScript, Arrays.asList(skuKeyLock),uuid);

                    //返回数据
                    return skuInfo;
                }else{
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //自旋
                    return getSkuInfoById(skuId);
                }
            }else{//缓存中有数据
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getSkuInfo(skuId);
    }
//================================================================================
    /*
    查询一级目录
     */
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    /*
    查询二级目录
     */
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
    }

    /*
    查询三级目录
     */
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
    }

    /*
    根据分类id,查询平台属性
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id,category2Id,category3Id);
    }

    //保存 平台属性 + 平台属性值
        //在这个实现类中,既有保存又有修改
    @Override
    @Transactional//添加事务
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if(baseAttrInfo.getId() == null){
            //保存
            //添加平台属性
            baseAttrInfoMapper.insert(baseAttrInfo);
        }else{
            //修改
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }
        //修改
        //当无法确定客户具体修改的id,可以先删除,再插入数据
        QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();
        baseAttrValueQueryWrapper.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(baseAttrValueQueryWrapper);
        //删除完成后,原本的Id没了

        //如下操作是保存
        //添加平台属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){
            //循环遍历 iter:增强for itar:普通for itco:迭代器
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }

    }

    //根据平台属性Id 获取平台属性值集合
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));

    }

    //根据平台属性Id,获取平台属性对象
    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        if(baseAttrInfo != null){
            //获取平台属性值集合,将属性值集合放入该对象
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        return baseAttrInfo;
    }

    //分页
    @Override
    public IPage getSpuInfoList(Page<SpuInfo> spuInfopage, SpuInfo spuInfo) {
        //构建查询条件
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id", spuInfo.getCategory3Id());
        //设置一个排序规则 mysql默认的败絮规则是升序asc;这里我们使用降序desc
        spuInfoQueryWrapper.orderByDesc("id");

        return spuInfoMapper.selectPage(spuInfopage, spuInfoQueryWrapper);
    }

    //获取销售属性集合
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //保存Spu属性
    @Override
    @Transactional//添加事务
    public void saveSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.insert(spuInfo);
        //获取图片列表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断不为空
        if(!CollectionUtils.isEmpty(spuImageList)){
            //循环遍历整个集合
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }

        //获取销售属性列表
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //判断
        if(!CollectionUtils.isEmpty(spuSaleAttrList)){
            //循环遍历
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                //获取销售属性值
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //判断
                if(!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        //前台传递的 json字符串没有 sale_attr_name
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }
    }

    //回显销售属性
    //根据spuId,获取销售属性+销售属性值
    @Override
    public List<SpuSaleAttr> getSupSaleAttrList(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectSpuSaleAttrList(spuId);

        return spuSaleAttrList;
    }

    //获取spu的图片列表
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
    }

    //大保存SkuInfo
    @Override
    @Transactional//添加事务
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
- skuInfo
- skuAttrValue:中间表,用来记录与平台上属性值的关系
- skuSaleAttrValue:sku与销售属性的关系
- skuImage:库存图片表
         */

        skuInfoMapper.insert(skuInfo);

        //sku 与平台属性值的关系
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {

                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }

        //sku与销售属性的关系
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if(!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {

                //添加数据
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }

        //SkuImage保存
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if(!CollectionUtils.isEmpty(skuImageList)){
            for (SkuImage skuImage : skuImageList) {

                skuImage.setSkuId(skuInfo.getId());
                skuImagerMapper.insert(skuImage);
            }
        }
    }

    //查询skuInfo 列表,带分页
    @Override
    public IPage<SkuInfo> getSkuinfoList(Page<SkuInfo> skuINfoPage) {

        return skuInfoMapper.selectPage(skuINfoPage, new QueryWrapper<SkuInfo>().orderByDesc("id"));

    }

    //商品上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setIsSale(1);
        skuInfo.setId(skuId);
        skuInfoMapper.updateById(skuInfo);
    }

    //商品下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    /**
     * 第五天
     * 获取sku基本信息与图片信息
     */
    //根据skuId查询skuInfo
    @Override
    @GmallCache(prefix = "skuInfo:")
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        //根据skuId查询图片列表集合
        List<SkuImage> skuImageList = skuImagerMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));

        skuInfo.setSkuImageList(skuImageList);

        return skuInfo;

    }

    //通过sku表的三级分类id获取一级分类名称、二级分类名称和三级分类名称
    @Override
    @GmallCache(prefix = "categoryViewByCategory:")
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //获取价格信息
    @Override
    @GmallCache(prefix = "skuPrice:")
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(skuInfo != null) {
            return skuInfo.getPrice();
        }
        return new BigDecimal(0);
    }

    //根据spuId,skuId查询销售属性集合
    //查出该商品的spu的所有销售属性和属性值
    @Override
    @GmallCache(prefix = "spuSaleAttrListCheck:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId, spuId);

    }

    //根据销售属性值进行切换商品
    //在后台需要查询出spuId下,对应多少sku
    @Override
    @GmallCache(prefix = "skuValueIds:")
    public Map getSkuValueIdsMap(Long spuId) {
        Map<Object, Object> map = new HashMap<>();
        List<Map> mapList = skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        if (mapList != null){
            //循环遍历
            for (Map skuMap : mapList) {
                map.put(skuMap.get("value_ids"), skuMap.get("sku_id"));
            }
        }
        //返回数据
        return map;
    }
}
